package com.dgut.service;

import com.dgut.vo.QueryVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dgut.mapper.StudentMapper;
import com.dgut.pojo.Student;
import com.dgut.pojo.StudentExample;
import com.dgut.util.StudentStateEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class StudentService {
    @Resource
    private StudentMapper studentMapper;

    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public PageInfo<Student> queryByPage(Integer pageNum, Integer pageSize, QueryVO vo) {
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        if (vo != null) {
            if (vo.getStuName() != null && vo.getStuName().trim().length() > 0) {
                criteria.andStunameLike("%" + vo.getStuName().trim() + "%");
            }
            if (vo.getStuNo() != null && vo.getStuNo().trim().length() > 0) {
                criteria.andStunoLike("%" + vo.getStuNo().trim() + "%");
            }
            if (vo.getSex() != null && vo.getSex() != -1) {
                criteria.andSexEqualTo(vo.getSex());
            }
        }
        criteria.andStateNotEqualTo(StudentStateEnum.DELETE.state);
        PageHelper.startPage(pageNum, pageSize);
        List<Student> students = studentMapper.selectByExample(studentExample);
        return new PageInfo<>(students);
    }
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public Student queryById(Integer stuId) {
        return studentMapper.selectByPrimaryKey(stuId);
    }
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int addStudent(Student student) {
        student.setState(StudentStateEnum.READING.state);
        student.setRegdate(new Date());;
        return studentMapper.insertSelective(student);
    }


    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int deleteStudent(Integer stuId) {
        Student student = new Student();
        student.setStuId(stuId);
        student.setState(StudentStateEnum.DELETE.state);
        return studentMapper.updateByPrimaryKeySelective(student);
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public int updateStudent(Student student) {
        return studentMapper.updateByPrimaryKeySelective(student);
    }
}
